import {FieldFiller, FieldFillType, IdGenerationStrategy, TableInfo} from "../types";

/**
 * 实体类的基类
 */
export abstract class BaseEntity {
  /**
   * 获取表的元数据信息
   * @returns 表信息对象
   */
  static getTableInfo<T>(): TableInfo<T> {
    // 首先尝试调用装饰器中定义的getTableInfo方法
    const proto = Object.getPrototypeOf(this);
    if (proto && proto.constructor && typeof proto.constructor.getTableInfo === 'function') {
      return proto.constructor.getTableInfo.call(this);
    }

    throw new Error(`实体 ${this.name} 缺少 @Table 装饰器或表信息未定义`);
  }

  /**
   * 处理实体的自动ID生成
   * 检查所有标记为generateId的字段，并根据数据库配置的ID生成策略生成ID
   * @param entity 要处理的实体实例
   * @returns 处理后的实体实例
   */
  static processAutoId<T extends BaseEntity>(entity: T): T {
    const tableInfo = this.getTableInfo<T>();
    const db = tableInfo.db;
    const primaryKeyConfig = db.primaryKeyConfig;

    // 如果全局配置禁用了自动生成ID，直接返回
    if (primaryKeyConfig.autoGenerateId === false) {
      return entity;
    }

    // 遍历所有列，查找需要生成ID的字段
    for (const columnName in tableInfo.columns) {
      const column = tableInfo.columns[columnName];

      // 如果字段配置了generateId并且当前值为undefined或null
      if (column.generateId && (entity[columnName as keyof T] === undefined || entity[columnName as keyof T] === null)) {
        // 如果是AUTO_INCREMENT策略，则跳过（由SQLite处理）
        if (primaryKeyConfig.idGenerationStrategy === IdGenerationStrategy.AUTO_INCREMENT &&
          column.type.toUpperCase() === 'INTEGER' &&
          column.autoIncrement) {
          continue;
        }

        // 生成新ID并赋值
        entity[columnName as keyof T] = db.generateId() as any;
      }
    }

    return entity;
  }

  /**
   * 处理实体的自动填充字段
   * @param entity 要处理的实体实例
   * @param fillType 填充类型
   * @returns 处理后的实体实例
   */
  static processAutoFill<T extends BaseEntity>(entity: T, fillType: FieldFillType): T {
    const tableInfo = this.getTableInfo<T>();
    const db = tableInfo.db;

    // 遍历所有列，查找需要填充的字段
    for (const columnName in tableInfo.columns) {
      const column = tableInfo.columns[columnName];

      // 检查字段是否需要填充
      if (column.fillType && (
        column.fillType === fillType ||
        column.fillType === FieldFillType.INSERT_UPDATE
      )) {
        // 获取填充器
        let filler: FieldFiller | undefined = column.filler;
        if (!filler) {
          // 如果没有配置填充器，尝试从数据库管理器获取
          filler = db.fieldFiller.get(columnName);
        }

        // 如果有填充器，则进行填充
        if (filler) {
          if (fillType === FieldFillType.INSERT || fillType === FieldFillType.INSERT_UPDATE) {
            if (filler.fillInsert) {
              entity[columnName as keyof T] = filler.fillInsert(entity, columnName) as any;
            }
          } else if (fillType === FieldFillType.UPDATE || fillType === FieldFillType.INSERT_UPDATE) {
            if (filler.fillUpdate) {
              entity[columnName as keyof T] = filler.fillUpdate(entity, columnName) as any;
            }
          }
        }
      }
    }

    return entity;
  }

  /**
   * 生成创建表的SQL语句
   * @returns SQL创建表语句
   */
  static getCreateTableSQL(): string {
    const tableInfo = this.getTableInfo<any>();

    // 构建列定义
    const columnDefs = []
    for (const columnName in tableInfo.columns) {
      const column = tableInfo.columns[columnName];
      let def = `${columnName} ${column.type}`;

      // 处理列约束
      if (column.primaryKey) {
        def += ' PRIMARY KEY';
        if (column.autoIncrement && column.type.toUpperCase() === 'INTEGER') {
          def += ' AUTOINCREMENT';
        }
      }

      if (column.notNull && !column.primaryKey) {
        def += ' NOT NULL';
      }

      if (column.unique && !column.primaryKey) {
        def += ' UNIQUE';
      }

      if (column.default !== undefined && column.default !== null) {
        if (typeof column.default === 'string') {
          def += ` DEFAULT '${column.default}'`;
        } else {
          def += ` DEFAULT ${column.default}`;
        }
      }

      // 处理外键
      if (column.foreignKey) {
        def += ` REFERENCES ${column.foreignKey.table}(${column.foreignKey.column})`;

        if (column.foreignKey.onDelete) {
          def += ` ON DELETE ${column.foreignKey.onDelete}`;
        }

        if (column.foreignKey.onUpdate) {
          def += ` ON UPDATE ${column.foreignKey.onUpdate}`;
        }
      }

      columnDefs.push(def);
    }

    // 构建CREATE TABLE语句
    let sql = `CREATE TABLE ${tableInfo.name} (\n  ${columnDefs.join(',\n  ')}\n)`;

    // 添加索引创建语句
    const indexStatements: string[] = [];
    if (tableInfo.indices && tableInfo.indices.length > 0) {
      for (const index of tableInfo.indices) {
        const uniqueClause = index.unique ? 'UNIQUE ' : '';
        indexStatements.push(
          `CREATE ${uniqueClause}INDEX ${index.name} ON ${tableInfo.name} (${index.columns.join(', ')})`
        );
      }
    }

    return [sql, ...indexStatements].join(';\n');
  }
}
